import { stringify } from 'querystring';
import { history, Reducer, Effect } from 'umi';
import { reloadAuthorized } from '@/utils/Authorized';
import { accountLogin } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery,checkHost } from '@/utils/utils';
import { message, Modal } from 'antd';
export interface StateType {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: '10';
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(accountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (!response) return message.error('账号或密码错误');
      if (response.status === 2) return message.error('您没有权限登录，请联系管理员');
      if (response.status === 3) return message.error('您已报名成功，管理员会及时为您审核，审核通过后即可进行登录，请耐心等待。');
      if (checkHost()) {
        if (response.openid){
          return Modal.confirm({
            title: '提示',
            content: '您已绑定微信账号，请通过微信账号进行登录',
            okText: '微信登录',
            onOk: () => {
              location.href = `/index/index/login_weixin`;
            },
          });
        }
      }

     
       
      message.success('登录成功');
      if (response.type === 2) {
        localStorage.setItem('antd-pro-authority', `["${response.type}"]`);
      } else {
        const power = response.types && response.types.power;
        localStorage.setItem('antd-pro-authority', `[${power}]`);
      }
      localStorage.setItem('name', response.name);
      localStorage.setItem('id_number', response.id_number);
      localStorage.setItem('type', response.type);
      localStorage.setItem('subjects', response.subjects);
      localStorage.setItem('id', response.id);
      localStorage.setItem('userinfo', JSON.stringify(response));
      const date = new Date();
      localStorage.setItem('logintime', date.getTime() + '');
      reloadAuthorized();
      const urlParams = new URL(window.location.href);
      const params = getPageQuery();
      let { redirect } = params as { redirect: string };
      if (redirect) {
        const redirectUrlParams = new URL(redirect);
        if (redirectUrlParams.origin === urlParams.origin) {
          redirect = redirect.substr(urlParams.origin.length);
          if (redirect.match(/^\/.*#/)) {
            // redirect = redirect.substr(redirect.indexOf('#') + 1);
            redirect = '/dashboard';
          }
        } else {
          redirect = '/dashboard';
        }
      }
      history.replace(redirect || '/');
      if(response.is_sw&&response.type !== 2){
        location.reload()
      }
    },

    logout() {
      const { redirect } = getPageQuery();
      // Note: There may be security issues, please note
      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          // search: stringify({
          //   redirect: window.location.href,
          // }),
        });
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};

export default Model;
